matplotlib[04]对象Line2D

摘要

点、线、面是视觉形态的基本构成元素。上一篇文章中引入了点的动画,这篇文章中我们将介绍线的动画。

效果图

安装ffmpeg

下载链接: https://ffmpeg.zeranoe.com/builds/

核心代码

1
2
line = Line2D([xlist[0]],[ylist[0]])
ax.add_line(line)

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!python2
#coding: utf-8
import sys
import numpy as np
import pylab as plt
from matplotlib.animation import FuncAnimation
from matplotlib.lines import Line2D
from matplotlib import animation
fig, ax = plt.subplots()
fig.set_tight_layout(True)
plt.rcParams['animation.ffmpeg_path'] =u'D:\\Python27_64\\Scripts\\ffmpeg.exe'
FFwriter = animation.FFMpegWriter()
plt.rcParams.update({'font.size':10})

fh=open("pmf.dat")
xlist=[]
ylist=[]
barlist=[]
xydict={}
for line in fh.readlines()[1:]:
x,y,bar=line.strip().split()
xydict[x]=y
x,y,bar=map(float,line.strip().split())
xlist.append(x)
ylist.append(y)

barlist.append(bar)

#http://www.tuicool.com/articles/Z7BzY3V
#plt.legend(loc=2,prop={'size': 9})
plt.xlabel('Z (Angstrom)')
plt.ylabel ('Free Energy (kCal/mol)')
plt.xlim(0,12)
plt.xticks([0,2,4,6,8,10,12])
plt.ylim(0,12)
plt.yticks([0,2,4,6,8,10,12])
# plt.plot(xlist,ylist,linewidth = 2.5, color = 'r')

# how to set line
# Line2D
line = Line2D([xlist[0]],[ylist[0]])

ax.add_line(line)
point_line,=plt.plot(xlist[0],ylist[0],'or',linewidth = 3, color = '#00FF7F')
# point_line2,=plt.plot(xlist[0],ylist[0],'or',linewidth = 3, color = '#00FF7F')
def update(i):
# pass
line.set_xdata(xlist[0:i])
line.set_ydata(ylist[0:i])
print i
#plt.plot(xlist[0:i],ylist[0:i],linewidth = 2.5, color = 'r')
# point_line2.set_xdata(xlist[0:i])
# point_line2.set_ydata(ylist[0:i])
point_line.set_xdata(xlist[i-1])
point_line.set_ydata(ylist[i-1])
return point_line
#http://ffmpeg.zeranoe.com/builds/
if __name__=='__main__':
anim=FuncAnimation(fig,update,frames=np.arange(0,8),interval=200)
# ffmpeg -i small.mp4 small.gif
# http://note.rpsh.net/posts/2015/04/21/mac-osx-ffmpeg-mp4-gif-convert/
#anim.save('linetest1.mp4',writer=FFwriter )
# anim.save('line.gif',writer=FFwriter )
plt.show()

数据data pmf.dat

1
2
3
4
5
6
7
8
9
1 7.2725 1
2 7.1284 2
3 7.0523 3
4 6.9731 3
5 6.8909 4
6 6.7982 4
7 6.7207 5
8 6.6218 6
9 6.5092 7

总结

图是由各种元素组成的。制作动画的前提是正确定位到该对象。对象的变化更新就形成了所谓的动画。